package com.ddpt.permission.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lh.center.common.util.AssertUtil;
import com.lh.center.extensions.api.utils.MD5Util;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@RefreshScope
public class WXLoginUtil {

    //扫码登陆请求的地址前缀
    @Value("${login.scanCodePrefixUrl:}")
    private String scanCodePrefixUrl;

    //根据用户扫码code获取openId的请求地址
    @Value("${login.getOpenIdByCodeUrl:}")
    private String getOpenIdByCodeUrl;

    //根据用户扫码code获取openId的请求地址
    @Value("${login.appId:}")
    private String appId;

    //根据用户扫码code获取openId的请求地址
    @Value("${login.appSecret:}")
    private String appSecret;

    public String getOpenId(String code){
        JSONObject paramBean = new JSONObject();
        paramBean.putOpt("code", code);
        paramBean.putOpt("appId", appId);
        paramBean.putOpt("sign", MD5Util.getMD5String(appId + appSecret + code).toLowerCase());
        // 请求合米接口换取用户信息
        String rs = HttpUtil.post(getOpenIdByCodeUrl, paramBean);
        JSONObject result = JSONUtil.parseObj(rs);
        AssertUtil.isTrue(result.getInt("status") == 300,"当前code已经使用过,请重新扫码登录");
        AssertUtil.isTrue(result.getInt("status") != 200, "获取用户授权信息失败:"+rs);
        return result.getJSONObject("payload").getStr("id");
    }

}
